// pages/device/agriculture.js
const global = getApp().globalData
import {
  getDeviceProperties,
  sendCmd
} from '../../utils/api.js'
Page({

  /**
   * 页面的初始数据
   */
  data: {
    device_name: '',
    device_id: '',
    result_code: '...',
    ctlMotor: '打开风扇',
    ctlLight: '打开电灯',
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      device_id: options.deviceId || wx.getStorageSync('device_id'),
      device_name: options.dname
    })
    wx.setStorageSync('device_id', options.deviceId)
    this.getProperties();
  },
  getProperties: function () {
    getDeviceProperties({
      'project_id': global.project_id || wx.getStorageSync('project_id'),
      'device_id': this.data.device_id
    }).then(res => {
      wx.stopPullDownRefresh({
        success: (res) => {},
      })
      var pro = res.shadow[0].reported.properties
      pro.lightImg = `../../images/Light${pro.LightStatus}.jpg`
      pro.motorImg = `../../images/FS${pro.MotorStatus}.gif`

      this.setData({
        property: pro,
        ctlLight: pro.LightStatus == 'ON' ? '关闭电灯' : '打开电灯',
        ctlMotor: pro.MotorStatus == 'ON' ? '关闭风扇' : '打开风扇'
      })

    })
  },
  switchLight: function (e) {
    let status = e.currentTarget.dataset.light
    this.setData({
      result_code: '中...'
    })
    var data = {
      "project_id": global.project_id,
      "device_id": this.data.device_id,
      "service_id": "Agriculture",
      "command_name": "Agriculture_Control_light",
      "paras": {
        "Light": status == "ON" ? "OFF" : "ON"
      }
    }
    sendCmd(data).then(res => {
      setTimeout(() => {
        this.getProperties()
      }, 2000);
    }, err => {
      console.log(err);
    })
  },
  switchMotor: function (e) {
    let status = e.currentTarget.dataset.motor
    this.setData({
      result_code: '...'
    })
    var data = {
      "project_id": global.project_id,
      "device_id": this.data.device_id,
      "service_id": "Agriculture",
      "command_name": "Agriculture_Control_Motor",
      "paras": {
        "Motor": status == "ON" ? "OFF" : "ON"
      }
    }
    sendCmd(data).then(res => {
      setTimeout(() => {
        this.getProperties()
      }, 2000);
    }, err => {
      console.log(err);
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getProperties()
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  // 返回
  back() {
    wx.switchTab({
      url: '/pages/home/index'
    })
  }
})